package com.kaoshi.myweb.webstruts.support;

import com.opensymphony.xwork2.validator.ValidationException;
import com.opensymphony.xwork2.validator.validators.FieldValidatorSupport;

public class ChineseValidator extends FieldValidatorSupport {
	private String mode = "some";

	@Override
	public void validate(Object object) throws ValidationException {
		final String fieldName = this.getFieldName();
		final String fieldValue = (String) this
				.getFieldValue(fieldName, object);
		
		
		if(fieldValue == null)
		{
			this.addFieldError(fieldName, object);
			return;
		}
		/**
		 * 字符串转换为 byte[],中文占两个位置，英文占一个位置
		 * 取length时，中文、英文各占一个位置
		 */
		final int bytes = fieldValue.getBytes().length;
		final int chars = fieldValue.length();

		if (mode.equals("none")) {
			if (chars != bytes)
				this.addFieldError(fieldName, object);
		}
		else if(mode.equals("some"))
		{
			if(chars == bytes || chars*2 == bytes)
				this.addFieldError(fieldName, object);
		}
		else if(mode.equals("all"))
		{
			if(chars*2 != bytes)
				this.addFieldError(fieldName, object);
		}
	}

	public String getMode() {
		return mode;
	}

	public void setMode(String mode) {
		this.mode = mode;
	}

}
